<template>
	<view class="container">
		<!-- 商品信息卡片 -->
		<view class="product-card">
			<!-- 商品图片区域 -->
			<view class="product-image-wrapper">
				<image 
					:src="testData.imageUrl || defaultImage"
					mode="widthFix"  
					class="product-image"
					@error="handleImageError"
				></image>
				<!-- 库存标签 -->
				<view class="stock-tag" :class="{ 'low-stock': testData.stock <= 5 }">
					{{ testData.stock > 0 ? `库存 ${testData.stock} 件` : '已售罄' }}
				</view>
			</view>
			
			<!-- 商品详情 -->
			<view class="product-detail">
				<text class="product-name">{{ testData.name || '商品名称' }}</text>
				<view class="product-price-wrapper">
					<text class="product-price">¥{{ (testData.price || 0).toFixed(2) }}</text>
				</view>
				
				<!-- 购买数量选择 -->
				<view class="quantity-wrapper">
					<text class="quantity-label">购买数量：</text>
					<view class="quantity-controls">
						<button 
							class="quantity-btn" 
							@click="decreaseQuantity"
							:disabled="quantity <= 1"
						>-</button>
						<input 
							class="quantity-input" 
							type="number" 
							v-model="quantity"
							min="1"
							max="testData.stock || 1"
							@input="handleQuantityChange"
						/>
						<button 
							class="quantity-btn" 
							@click="increaseQuantity"
							:disabled="quantity >= (testData.stock || 1)"
						>+</button>
					</view>
				</view>
				
				<!-- 总价 -->
				<view class="total-price-wrapper">
					<text class="total-label">应付金额：</text>
					<text class="total-price">¥{{ (totalAmount).toFixed(2) }}</text>
				</view>
			</view>
		</view>
		
		<!-- 支付方式选择 -->
		<view class="payment-methods">
			<text class="section-title">选择支付方式</text>
			
			<view 
				class="payment-item" 
				:class="{ active: selectedPayment === 'wechat' }"
				@click="selectPayment('wechat')"
			>
				<view class="payment-icon">
					<image src="/static/微信.png" mode="aspectFit" class="icon-img"></image>
				</view>
				<text class="payment-text">微信支付</text>
				<view class="radio-icon" :class="{ checked: selectedPayment === 'wechat' }">✓</view>
			</view>
			
			<view 
				class="payment-item" 
				:class="{ active: selectedPayment === 'alipay' }"
				@click="selectPayment('alipay')"
			>
				<view class="payment-icon">
					<image src="/static/支付宝.png" mode="aspectFit" class="icon-img"></image>
				</view>
				<text class="payment-text">支付宝支付</text>
				<view class="radio-icon" :class="{ checked: selectedPayment === 'alipay' }">✓</view>
			</view>
		</view>
		
		<!-- 支付按钮区域（底部固定） -->
		<view class="pay-footer">
			<view class="footer-total">
				<text class="footer-total-label">总计：</text>
				<text class="footer-total-price">¥{{ (totalAmount).toFixed(2) }}</text>
			</view>
			<button 
				class="pay-btn" 
				@click="handlePay"
				:disabled="!testData.stock || testData.stock <= 0 || loading"
			>
				<text v-if="loading" class="loading-text">支付中...</text>
				<text v-else class="pay-text">确认支付</text>
			</button>
		</view>
	</view>
</template>

<script>
	let tag = 'purchase'
	
	export default {
		data() {
			return {
				testData: {}, // 商品数据
				quantity: 1, // 购买数量
				selectedPayment: 'wechat', // 默认选中微信支付
				loading: false, // 支付加载状态
				defaultImage: '/static/default-product.png', // 默认商品图片
			}
		},
		
		computed: {
			// 计算总价
			totalAmount() {
				const price = parseFloat(this.testData.price || 0);
				const qty = parseInt(this.quantity || 1);
				return price * qty;
			}
		},
		
		methods: {
			// ==================== 数量控制方法 ====================
			// 减少数量
			decreaseQuantity() {
				if (this.quantity > 1) {
					this.quantity--;
				}
			},
			
			// 增加数量
			increaseQuantity() {
				const maxQty = this.testData.stock || 1;
				if (this.quantity < maxQty) {
					this.quantity++;
				}
			},
			
			// 数量输入变化处理
			handleQuantityChange() {
				let qty = parseInt(this.quantity) || 1;
				const maxQty = this.testData.stock || 1;
				
				// 限制数量范围
				if (qty < 1) {
					this.quantity = 1;
				} else if (qty > maxQty) {
					this.quantity = maxQty;
					uni.showToast({
						title: `库存仅剩${maxQty}件`,
						icon: 'none',
						duration: 1500
					});
				}
			},
			
			// ==================== 支付方式选择 ====================
			selectPayment(type) {
				this.selectedPayment = type;
				this.$log.info(tag, `选择支付方式：${type === 'wechat' ? '微信支付' : '支付宝支付'}`);
			},
			
			// ==================== 图片加载错误处理 ====================
			handleImageError() {
				this.testData.imageUrl = this.defaultImage;
			},
			
			// ==================== 支付核心逻辑 ====================
			// 处理支付点击
			handlePay() {
				if (!this.testData.stock || this.testData.stock <= 0) {
					uni.showToast({
						title: '商品已售罄',
						icon: 'none',
						duration: 1500
					});
					return;
				}
				
				// 确认支付方式
				const payTypeText = this.selectedPayment === 'wechat' ? '微信支付' : '支付宝支付';
				uni.showModal({
					title: '确认支付',
					content: `您将使用${payTypeText}支付¥${this.totalAmount.toFixed(2)}，是否确认？`,
					success: (res) => {
						if (res.confirm) {
							this.createOrder();
						}
					}
				});
			},
			
			// 创建订单
			createOrder() {
				this.loading = true;
				this.$log.info(tag, "开始创建订单，数量：", this.quantity);
				
				uni.request({
					url: `${this.$constant.BASE_URL}/api/order/create4Ma`,
					method: 'POST',
					header: {
						'Authorization': this.$loginManager.getToken(),
						'content-type': 'application/json'
					},
					data: {
						'amount': this.quantity, // 购买数量
						'machineNo': this.$constant.MACHINE_NO,
						'productId': this.testData.id,
						'totalPrice': this.totalAmount, // 总价
					},
					success: (res) => {
						this.$log.info(tag, '订单创建请求成功 - 响应数据:', res.data);
						
						// 检查响应数据是否完整
						if (!res.data) {
							this.$log.error(tag, "响应数据为空");
							uni.showToast({ title: "服务器响应错误", icon: "none" });
							this.loading = false;
							return;
						}
						
						if (res.data.code == 200) {
							this.$log.info(tag, "订单创建成功");
							
							// 检查订单号是否存在
							if (res.data.orderNo) {
								this.$log.info(tag, `订单号: ${res.data.orderNo}`);
								// 订单创建成功后，调用支付接口
								this.payOrder(res.data.orderNo);
							} else {
								this.$log.error(tag, "订单号不存在");
								uni.showToast({ title: "订单创建异常", icon: "none" });
								this.loading = false;
							}
						} else {
							this.$log.error(tag, `创建订单失败: ${res.data.msg || '未知错误'}`);
							uni.showToast({ title: res.data.msg || "创建订单失败", icon: "none" });
							this.loading = false;
						}
					},
					fail: (error) => {
						this.$log.error(tag, "订单创建网络请求失败:", error);
						uni.showToast({ title: "网络请求失败", icon: "none" });
						this.loading = false;
					}
				});
			},
			
			// 支付订单
			payOrder(orderNo) {
				this.$log.info(tag, `开始支付订单: ${orderNo}，支付方式：${this.selectedPayment}`);
				
				// 确保订单号有效
				if (!orderNo) {
					this.$log.error(tag, "订单号无效");
					uni.showToast({ title: "订单号无效", icon: "none" });
					this.loading = false;
					return;
				}
				
				// 根据选择的支付方式调用不同的支付接口
				const payUrl = this.selectedPayment === 'wechat' 
					? `${this.$constant.BASE_URL}/wxpay/notify/pay/${orderNo}`
					: `${this.$constant.BASE_URL}/alipay/notify/pay/${orderNo}`;
				
				uni.request({
					url: payUrl,
					method: 'GET',
					header: {
						'Authorization': this.$loginManager.getToken(),
						'content-type': 'application/json'
					},
					success: (res) => {
						this.$log.info(tag, `${this.selectedPayment}支付请求成功 - 响应数据:`, res.data);
						
						// 支付成功后展示提示并跳转到订单详情页
						uni.showToast({
							icon: 'success',
							title: '支付成功',
							duration: 1500
						});
						
						// 跳转到订单详情页并携带订单号
						setTimeout(() => {
							this.loading = false;
							uni.navigateTo({
								url: `/pages/order/order?orderNo=${orderNo}`
							});
						}, 1500);
					},
					fail: (error) => {
						this.$log.error(tag, `${this.selectedPayment}支付请求失败:`, error);
						uni.showToast({
							icon: 'error',
							title: `${this.selectedPayment === 'wechat' ? '微信' : '支付宝'}支付请求失败`,
							duration: 1500
						});
						this.loading = false;
					}
				});
			},
		},
		
		onLoad(parameters) {
			this.$log.info(tag, `onLoad`);
			if (parameters && parameters.product) {
				try {
					let productJSONString = decodeURIComponent(parameters.product);
					let product = JSON.parse(productJSONString);
					this.testData = product;
					this.$log.info(tag, `商品信息: ${product.name}, 价格: ${product.price}, 库存: ${product.stock}`);
					
					// 初始化购买数量为1，不超过库存
					this.quantity = Math.min(1, product.stock || 1);
				} catch (e) {
					this.$log.error(tag, "解析商品数据失败:", e);
					uni.showToast({ title: "商品数据错误", icon: "none" });
				}
			} else {
				this.$log.error(tag, "未接收到商品参数");
				uni.showToast({ title: "未找到商品信息", icon: "none" });
			}
		},
		
		onShow() {
			this.$log.info(tag, `onShow`);
		},
		
		onReady() {
			this.$log.info(tag, `onReady`);
		},
		
		onHide() {
			this.$log.info(tag, `onHide`);
		},
		
		onUnload() {
			this.$log.info(tag, `onUnload`);
		},
	}
</script>

<style scoped>
	/* 基础容器 */
	.container {
		padding: 20rpx;
		display: flex;
		flex-direction: column;
		background-color: #f5f5f5;
		min-height: 110vh;
		box-sizing: border-box;
	}
	
	/* 商品卡片 */
	.product-card {
		background-color: #fff;
		border-radius: 20rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
	}
	
	/* 商品图片区域 - 调整为自适应高度，保证图片完整显示 */
	.product-image-wrapper {
		position: relative;
		width: 100%;
		border-radius: 12rpx;
		overflow: hidden;
		/* margin-bottom: 24rpx; */
		/* 新增：弹性布局居中，背景色兜底 */
		display: flex;
		justify-content: center;
		align-items: flex-start;
		background-color: #f9f9f9;
		/* 保留最大高度限制，避免图片过高 */
		max-height: 800rpx;
	}
	
	/* 商品图片 - 关键调整：宽度100%，高度自适应，完整显示 */
	.product-image {
		width: 100%;
		height: 100%;
		object-fit: contain; /* 强制图片完整显示，不裁剪 */
	}
	
	/* 库存标签 */
	.stock-tag {
		position: absolute;
		top: 20rpx;
		left: 20rpx;
		background-color: rgba(0, 0, 0, 0.7);
		color: #fff;
		padding: 8rpx 16rpx;
		border-radius: 20rpx;
		font-size: 24rpx;
		/* 确保标签在图片上方 */
		z-index: 10;
	}
	
	.stock-tag.low-stock {
		background-color: #ff6b6b;
	}
	
	/* 商品详情 */
	.product-detail {
		display: flex;
		flex-direction: column;
		gap: 20rpx;
	}
	
	.product-name {
		font-size: 36rpx;
		font-weight: 600;
		color: #333;
		line-height: 1.4;
	}
	
	.product-price-wrapper {
		display: flex;
		align-items: baseline;
	}
	
	.product-price {
		font-size: 48rpx;
		font-weight: bold;
		color: #e53e3e;
	}
	
	/* 数量选择 */
	.quantity-wrapper {
		display: flex;
		align-items: center;
		padding: 16rpx 0;
		border-top: 1rpx solid #eee;
		border-bottom: 1rpx solid #eee;
	}
	
	.quantity-label {
		font-size: 30rpx;
		color: #666;
		margin-right: 20rpx;
	}
	
	.quantity-controls {
		display: flex;
		align-items: center;
	}
	
	.quantity-btn {
		width: 60rpx;
		height: 60rpx;
		background-color: #f5f5f5;
		border: none;
		border-radius: 8rpx;
		font-size: 36rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #333;
	}
	
	.quantity-btn:disabled {
		background-color: #eee;
		color: #ccc;
	}
	
	.quantity-input {
		width: 100rpx;
		height: 60rpx;
		text-align: center;
		font-size: 30rpx;
		border: 1rpx solid #eee;
		border-left: none;
		border-right: none;
	}
	
	/* 总价 */
	.total-price-wrapper {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding-top: 16rpx;
	}
	
	.total-label {
		font-size: 30rpx;
		color: #666;
	}
	
	.total-price {
		font-size: 36rpx;
		font-weight: bold;
		color: #e53e3e;
	}
	
	/* 支付方式选择 */
	.payment-methods {
		background-color: #fff;
		border-radius: 20rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
	}
	
	.section-title {
		font-size: 32rpx;
		font-weight: 600;
		color: #333;
		margin-bottom: 24rpx;
		display: block;
	}
	
	.payment-item {
		display: flex;
		align-items: center;
		padding: 20rpx;
		border-radius: 12rpx;
		margin-bottom: 16rpx;
		border: 2rpx solid #eee;
		transition: all 0.2s ease;
	}
	
	.payment-item.active {
		border-color: #07c160;
		background-color: rgba(7, 193, 96, 0.05);
	}
	
	.payment-icon {
		width: 60rpx;
		height: 60rpx;
		margin-right: 20rpx;
	}
	
	.icon-img {
		width: 100%;
		height: 100%;
	}
	
	.payment-text {
		flex: 1;
		font-size: 32rpx;
		color: #333;
	}
	
	.radio-icon {
		width: 40rpx;
		height: 40rpx;
		border-radius: 50%;
		border: 2rpx solid #ccc;
		display: flex;
		align-items: center;
		justify-content: center;
		color: transparent;
		font-size: 24rpx;
	}
	
	.radio-icon.checked {
		background-color: #07c160;
		border-color: #07c160;
		color: #fff;
	}
	
	/* 底部支付栏 */
	.pay-footer {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #fff;
		padding: 20rpx 30rpx;
		box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.05);
		display: flex;
		align-items: center;
		gap: 20rpx;
		z-index: 99;
	}
	
	.footer-total {
		flex: 1;
	}
	
	.footer-total-label {
		font-size: 28rpx;
		color: #666;
	}
	
	.footer-total-price {
		font-size: 36rpx;
		font-weight: bold;
		color: #e53e3e;
	}
	
	.pay-btn {
		min-width: 240rpx;
		height: 88rpx;
		background-color: #07c160;
		color: #fff;
		border: none;
		border-radius: 44rpx;
		font-size: 32rpx;
		font-weight: 600;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.pay-btn:disabled {
		background-color: #ccc;
	}
	
	.loading-text {
		font-size: 28rpx;
	}
	
	/* 适配底部安全区 */
	/* #ifdef MP-WEIXIN */
	.pay-footer {
		padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
	}
	/* #endif */
	
	/* 响应式调整 */
	@media (max-width: 375px) {
		.product-image-wrapper {
			max-height: 800rpx; /* 小屏幕缩小最大高度 */
		}
		
		.pay-btn {
			min-width: 200rpx;
			height: 80rpx;
			font-size: 28rpx;
		}
	}
</style>